package com.maodou.core.ui.theme

import android.content.res.Configuration
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
 * 主题管理器
 * 负责管理应用主题状态和切换逻辑
 */
class ThemeManager {
    
    private val _themeConfig = MutableStateFlow(ThemeConfig())
    val themeConfig: StateFlow<ThemeConfig> = _themeConfig.asStateFlow()
    
    /**
     * 更新主题类型
     */
    fun updateThemeType(themeType: ThemeType) {
        _themeConfig.value = _themeConfig.value.copy(themeType = themeType)
    }
    
    /**
     * 更新深色模式类型
     */
    fun updateDarkModeType(darkModeType: DarkModeType) {
        _themeConfig.value = _themeConfig.value.copy(darkModeType = darkModeType)
    }
    
    /**
     * 更新字体大小类型
     */
    fun updateFontSizeType(fontSizeType: FontSizeType) {
        _themeConfig.value = _themeConfig.value.copy(fontSizeType = fontSizeType)
    }
    
    /**
     * 更新布局密度类型
     */
    fun updateLayoutDensityType(layoutDensityType: LayoutDensityType) {
        _themeConfig.value = _themeConfig.value.copy(layoutDensityType = layoutDensityType)
    }
    
    /**
     * 切换动态颜色
     */
    fun toggleDynamicColor() {
        _themeConfig.value = _themeConfig.value.copy(dynamicColor = !_themeConfig.value.dynamicColor)
    }
    
    /**
     * 切换高对比度
     */
    fun toggleHighContrast() {
        _themeConfig.value = _themeConfig.value.copy(highContrast = !_themeConfig.value.highContrast)
    }
    
    /**
     * 重置为默认配置
     */
    fun resetToDefault() {
        _themeConfig.value = ThemeConfig()
    }
    
    /**
     * 应用完整配置
     */
    fun applyConfig(config: ThemeConfig) {
        _themeConfig.value = config
    }
    
    companion object {
        @Volatile
        private var INSTANCE: ThemeManager? = null
        
        fun getInstance(): ThemeManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: ThemeManager().also { INSTANCE = it }
            }
        }
    }
}

/**
 * 主题解析器
 * 负责根据配置解析出实际的主题数据
 */
object ThemeResolver {
    
    /**
     * 解析是否为深色模式
     */
    @Composable
    fun resolveDarkMode(darkModeType: DarkModeType): Boolean {
        return when (darkModeType) {
            DarkModeType.LIGHT -> false
            DarkModeType.DARK -> true
            DarkModeType.SYSTEM -> isSystemInDarkTheme()
        }
    }
    
    /**
     * 解析完整主题
     */
    @Composable
    fun resolveTheme(config: ThemeConfig): AppTheme {
        val context = LocalContext.current
        val configuration = LocalConfiguration.current
        val isDark = resolveDarkMode(config.darkModeType)
        
        // 解析颜色方案
        val colorScheme = when {
            config.dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
                if (isDark) {
                    dynamicDarkColorScheme(context)
                } else {
                    dynamicLightColorScheme(context)
                }
            }
            else -> {
                ThemeFactory.createColorScheme(
                    themeType = config.themeType,
                    isDark = isDark,
                    highContrast = config.highContrast
                )
            }
        }
        
        // 解析字体排版
        val typography = ThemeFactory.createTypography(config.fontSizeType)
        
        // 解析间距配置
        val spacing = ThemeFactory.createSpacing(config.layoutDensityType)
        
        // 解析形状配置
        val shapes = ThemeFactory.createShapes()
        
        return AppTheme(
            colorScheme = colorScheme,
            typography = typography,
            spacing = spacing,
            shapes = shapes,
            config = config
        )
    }
    
    /**
     * 获取自适应尺寸
     */
    @Composable
    fun resolveAdaptiveSize(adaptiveDimensions: AdaptiveDimensions): androidx.compose.ui.unit.Dp {
        val configuration = LocalConfiguration.current
        val screenWidth = configuration.screenWidthDp.dp
        return adaptiveDimensions.getSize(screenWidth)
    }
    
    /**
     * 解析自适应尺寸配置
     */
    @Composable
    fun resolveAdaptiveDimensions(): AdaptiveDimensions {
        val configuration = LocalConfiguration.current
        val screenWidth = configuration.screenWidthDp.dp
        
        // 返回一个综合的自适应尺寸配置，根据屏幕大小调整
        return AdaptiveDimensions(
            small = when {
                screenWidth < Breakpoints.Small -> Spacing.Small
                screenWidth < Breakpoints.Medium -> Spacing.Default
                else -> Spacing.Medium
            },
            medium = when {
                screenWidth < Breakpoints.Small -> Spacing.Default
                screenWidth < Breakpoints.Medium -> Spacing.Medium
                else -> Spacing.Large
            },
            large = when {
                screenWidth < Breakpoints.Small -> Spacing.Medium
                screenWidth < Breakpoints.Medium -> Spacing.Large
                else -> Spacing.ExtraLarge
            },
            extraLarge = when {
                screenWidth < Breakpoints.Small -> Spacing.Large
                screenWidth < Breakpoints.Medium -> Spacing.ExtraLarge
                else -> Spacing.Huge
            }
        )
    }
    
    /**
     * 判断是否为大屏设备
     */
    @Composable
    fun isLargeScreen(): Boolean {
        val configuration = LocalConfiguration.current
        return configuration.screenWidthDp >= 840
    }
    
    /**
     * 判断是否为平板设备
     */
    @Composable
    fun isTablet(): Boolean {
        val configuration = LocalConfiguration.current
        return configuration.screenWidthDp >= 600 && 
               configuration.smallestScreenWidthDp >= 600
    }
    
    /**
     * 获取屏幕方向
     */
    @Composable
    fun getOrientation(): Int {
        val configuration = LocalConfiguration.current
        return configuration.orientation
    }
    
    /**
     * 判断是否为横屏
     */
    @Composable
    fun isLandscape(): Boolean {
        return getOrientation() == Configuration.ORIENTATION_LANDSCAPE
    }
    
    /**
     * 判断是否为竖屏
     */
    @Composable
    fun isPortrait(): Boolean {
        return getOrientation() == Configuration.ORIENTATION_PORTRAIT
    }
}

/**
 * 主题工具类
 * 提供主题相关的工具方法
 */
object ThemeUtils {
    
    /**
     * 获取主题类型的显示名称
     */
    fun getThemeTypeName(themeType: ThemeType): String {
        return when (themeType) {
            ThemeType.DEFAULT -> "默认主题"
            ThemeType.GREEN -> "绿色主题"
            ThemeType.PURPLE -> "紫色主题"
            ThemeType.SYSTEM -> "跟随系统"
        }
    }
    
    /**
     * 获取深色模式类型的显示名称
     */
    fun getDarkModeTypeName(darkModeType: DarkModeType): String {
        return when (darkModeType) {
            DarkModeType.LIGHT -> "浅色模式"
            DarkModeType.DARK -> "深色模式"
            DarkModeType.SYSTEM -> "跟随系统"
        }
    }
    
    /**
     * 获取字体大小类型的显示名称
     */
    fun getFontSizeTypeName(fontSizeType: FontSizeType): String {
        return when (fontSizeType) {
            FontSizeType.COMPACT -> "紧凑"
            FontSizeType.DEFAULT -> "默认"
            FontSizeType.RELAXED -> "宽松"
        }
    }
    
    /**
     * 获取布局密度类型的显示名称
     */
    fun getLayoutDensityTypeName(layoutDensityType: LayoutDensityType): String {
        return when (layoutDensityType) {
            LayoutDensityType.COMPACT -> "紧凑"
            LayoutDensityType.DEFAULT -> "默认"
            LayoutDensityType.COMFORTABLE -> "舒适"
        }
    }
    
    /**
     * 检查是否支持动态颜色
     */
    fun supportsDynamicColor(): Boolean {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
    }
    
    /**
     * 获取所有可用的主题类型
     */
    fun getAllThemeTypes(): List<ThemeType> {
        return ThemeType.values().toList()
    }
    
    /**
     * 获取所有可用的深色模式类型
     */
    fun getAllDarkModeTypes(): List<DarkModeType> {
        return DarkModeType.values().toList()
    }
    
    /**
     * 获取所有可用的字体大小类型
     */
    fun getAllFontSizeTypes(): List<FontSizeType> {
        return FontSizeType.values().toList()
    }
    
    /**
     * 获取所有可用的布局密度类型
     */
    fun getAllLayoutDensityTypes(): List<LayoutDensityType> {
        return LayoutDensityType.values().toList()
    }
}

/**
 * 主题预设
 * 提供一些常用的主题配置预设
 */
object ThemePresets {
    
    /**
     * 默认配置
     */
    val Default = ThemeConfig()
    
    /**
     * 深色模式配置
     */
    val Dark = ThemeConfig(
        darkModeType = DarkModeType.DARK
    )
    
    /**
     * 绿色主题配置
     */
    val Green = ThemeConfig(
        themeType = ThemeType.GREEN
    )
    
    /**
     * 紫色主题配置
     */
    val Purple = ThemeConfig(
        themeType = ThemeType.PURPLE
    )
    
    /**
     * 紧凑布局配置
     */
    val Compact = ThemeConfig(
        fontSizeType = FontSizeType.COMPACT,
        layoutDensityType = LayoutDensityType.COMPACT
    )
    
    /**
     * 舒适布局配置
     */
    val Comfortable = ThemeConfig(
        fontSizeType = FontSizeType.RELAXED,
        layoutDensityType = LayoutDensityType.COMFORTABLE
    )
    
    /**
     * 高对比度配置
     */
    val HighContrast = ThemeConfig(
        highContrast = true,
        dynamicColor = false
    )
    
    /**
     * 无障碍配置
     */
    val Accessibility = ThemeConfig(
        fontSizeType = FontSizeType.RELAXED,
        layoutDensityType = LayoutDensityType.COMFORTABLE,
        highContrast = true,
        dynamicColor = false
    )
}